﻿using Micro.Extensions.Utilities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace Mirco.Extensions.Web
{
    public class GlobalExceptionFilter : ExceptionFilterAttribute
    {
        private readonly ILogger<GlobalExceptionFilter> _logger;

        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        public override void OnException(ExceptionContext context)
        {
            if (context.Exception is ComResultException comResultException)
            {
                _logger.LogWarning(context.Exception, context.Exception.Message);

                var bizResult = ComResult.Failed(comResultException.Code, comResultException.Msg);
                context.Result = new ObjectResult(bizResult);
                context.ExceptionHandled = true;
            }
            else
            {
                _logger.LogError(context.Exception, context.Exception.Message);

                var result = ComResult.Failed(1002, context.Exception.Message);
                context.Result = new ObjectResult(result);
                context.ExceptionHandled = true;
            }
        }
    }
}
